package com.wbao.dianniu.tabstrip.fragments;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.data.HeadInfoData;
import com.wbao.dianniu.data.SyncInfoData;
import com.wbao.dianniu.fragment.LazyLoadBaseFragment;
import com.wbao.dianniu.im.FollowListActivity;
import com.wbao.dianniu.listener.IHeadImageListener;
import com.wbao.dianniu.listener.IHeadInfoListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.manager.HeadInfoManager;
import com.wbao.dianniu.ui.FansListActivity;
import com.wbao.dianniu.ui.MyScoreActivity;
import com.wbao.dianniu.ui.PartnerActivity;
import com.wbao.dianniu.update.HeadImageManger;
import com.wbao.dianniu.ui.IndustryAuthActivity;
import com.wbao.dianniu.ui.MyAmActivity;
import com.wbao.dianniu.ui.MyCollectionActivity;
import com.wbao.dianniu.ui.MyQAnswerActivity;
import com.wbao.dianniu.ui.MyQRCodeActivity;
import com.wbao.dianniu.ui.PerfectInfoActivity;
import com.wbao.dianniu.ui.SettingActivity;
import com.wbao.dianniu.update.ScoreChangeManager;
import com.wbao.dianniu.update.ErrorDialogHelper;
import com.wbao.dianniu.utils.GlideCircleTransform;
import com.wbao.dianniu.utils.JsonUtil;
import com.wbao.dianniu.utils.PermissionUtils;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.Utils;

import java.io.File;
import java.util.ArrayList;


/**
 * 我
 *
 * @author yejianjun
 */
public class FourthFragment extends LazyLoadBaseFragment implements OnClickListener, IHeadImageListener, ScoreChangeManager.IScoreChangeListener, IHeadInfoListener {

    /**
     * 头像
     */
    private ImageView headIV;
    /**
     * 个人资料信息
     */
    private RelativeLayout headInfoRl;
    /**
     * 完善资料
     */
    private RelativeLayout prefectInfoRl;
    /**
     * 行业认证
     */
    private RelativeLayout rl_auth;
    /**
     * 我的问答
     */
    private RelativeLayout rl_myquestion;
    /**
     * 与我相关
     */
    private RelativeLayout rl_anonymous;
    /**
     * 设置
     */
    private RelativeLayout rl_setting;
    /**
     * 我的收藏
     */
    private RelativeLayout rl_mycollection;
    /**
     * 我的积分
     */
//    private RelativeLayout rl_score;
    /**
     * 扫一扫
     */
    private RelativeLayout rl_scan;
    private RelativeLayout rl_partner;
    private TextView partnerScoreTV;
    private TextView nickNameTV;
    private TextView labelTV;
    private TextView signateTV;
    private Dialog dialog;
    private ImageButton qrCodeBtn;
    private ImageView sexIV;
    private ImageView partnerIV;
    private ImageView addV;
    //    private TextView myScoreTV;
    private HeadImageManger headImageManger;
    private ScoreChangeManager scoreChangeManager;
    public static final String ACTION_SCORE_UPDATE = "com.wbao.dianniu.action.score.update";
    public static final String INTENT_DATA = "intent.socre.update.json";
    private ScoreUpdateReceiver scoreUpdateReceiver;
    private HeadInfoManager headInfoManager;
    private RefreshLayout swipeLayout;
    private TextView authStatusTV;
    private TextView followTV;
    private TextView fansTV;
    private LinearLayout ll_follow, ll_fans, ll_score;


    public static FourthFragment instance() {
        FourthFragment view = new FourthFragment();
        //在该Fragment的构造函数中注册mTouchListener的回调
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private void initManager() {
        headImageManger = HeadImageManger.getInstance();
        headImageManger.addListener(this);
        scoreChangeManager = ScoreChangeManager.getInstance();
        scoreChangeManager.addScoreChangeListener(this);
        headInfoManager = new HeadInfoManager(getContext());
        headInfoManager.addHeadListener(this);
    }

    @Override
    public void onDestroy() {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (null != headImageManger) {
            headImageManger.removeListener(this);
        }
        if (null != scoreChangeManager) {
            scoreChangeManager.removeScoreChangeListener(this);
        }
        if (null != scoreUpdateReceiver) {
            // 注销广播
            getContext().unregisterReceiver(scoreUpdateReceiver);
        }
        super.onDestroy();
    }

    /*@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fourth_fragment, null);
        initFragmentView(view);
        addHeadView(view);
        addListener();
        reqData();
        return view;
    }*/

    private void addListener() {
        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                reqData();
            }
        });

    }

    private void initFragmentView(View view) {
        /*pullListView = (PullToRefreshListView) view.findViewById(R.id.fourth_pullToRefreshView);
        pullListView.setMode(PullToRefreshBase.Mode.PULL_DOWN_TO_REFRESH);
        pullListView.setOnRefreshListener(onRefreshListener);
        myListView = pullListView.getRefreshableView();
        registerForContextMenu(myListView);*/
        swipeLayout = (RefreshLayout) view.findViewById(R.id.swipe_container);

        qrCodeBtn = (ImageButton) view.findViewById(R.id.qrcode_Imagebutton);
    }

    private void addHeadView(View headView) {
        headIV = (ImageView) headView.findViewById(R.id.headIcon);
        headInfoRl = (RelativeLayout) headView.findViewById(R.id.head_info_relative);
        rl_auth = (RelativeLayout) headView.findViewById(R.id.rl_Auth);
        prefectInfoRl = (RelativeLayout) headView.findViewById(R.id.rl_prefect_info);
        rl_myquestion = (RelativeLayout) headView.findViewById(R.id.rl_myquestion);
        rl_anonymous = (RelativeLayout) headView.findViewById(R.id.rl_anonymous);
        rl_setting = (RelativeLayout) headView.findViewById(R.id.rl_sets);
        rl_mycollection = (RelativeLayout) headView.findViewById(R.id.rl_collection);
        rl_scan = (RelativeLayout) headView.findViewById(R.id.rl_scan);
        rl_partner = (RelativeLayout) headView.findViewById(R.id.rl_partner);

        fansTV = (TextView) headView.findViewById(R.id.my_fans_count);
        followTV = (TextView) headView.findViewById(R.id.my_follow_count);
        authStatusTV = (TextView) headView.findViewById(R.id.auth_user_status);
        partnerScoreTV = (TextView) headView.findViewById(R.id.my_score_count);
        nickNameTV = (TextView) headView.findViewById(R.id.dn_name);
        labelTV = (TextView) headView.findViewById(R.id.label_id);
        sexIV = (ImageView) headView.findViewById(R.id.user_sex);
        partnerIV = (ImageView) headView.findViewById(R.id.user_partner);
        addV = (ImageView) headView.findViewById(R.id.add_v_iv);
        signateTV = (TextView) headView.findViewById(R.id.dn_signature);
        ll_follow = (LinearLayout) headView.findViewById(R.id.follow_ll);
        ll_fans = (LinearLayout) headView.findViewById(R.id.fans_ll);
        ll_score = (LinearLayout) headView.findViewById(R.id.score_ll);

        PictureDownloadUtils.displayHeadImage(getContext(), headIV, GlobalContext.getHeadPic());

        nickNameTV.setText(GlobalContext.getNiceName() == null ? "" : GlobalContext.getNiceName());
        labelTV.setText(GlobalContext.getLabel() == null ? "" : GlobalContext.getLabel());
        Utils.showSex(headView.getContext(), GlobalContext.getSex(), sexIV);
        if (GlobalContext.getIndustryAuthority()) {
            addV.setVisibility(View.VISIBLE);
            authStatusTV.setText(getResources().getString(R.string.already_auth));
            authStatusTV.setTextColor(getResources().getColor(R.color.edit_hint_color));
        } else {
            addV.setVisibility(View.GONE);
            authStatusTV.setText(getResources().getString(R.string.no_auth));
            authStatusTV.setTextColor(getResources().getColor(R.color.already_auth_color));
        }

        signateTV.setText(GlobalContext.getSignate() == null ? "简介：暂无" : "简介：" + GlobalContext.getSignate());
        if (GlobalContext.getPerfectData()) {
            prefectInfoRl.setVisibility(View.GONE);
        } else {
            prefectInfoRl.setVisibility(View.VISIBLE);
        }
        GlobalUserData userData = new GlobalUserData();
        partnerScoreTV.setText(userData.getScore() + "");
        if (userData.getPartner() == 1) {
            partnerIV.setVisibility(View.VISIBLE);
        } else {
            partnerIV.setVisibility(View.GONE);
        }

        headIV.setOnClickListener(this);
        headInfoRl.setOnClickListener(this);
        rl_auth.setOnClickListener(this);
        prefectInfoRl.setOnClickListener(this);
        rl_myquestion.setOnClickListener(this);
        rl_anonymous.setOnClickListener(this);
        rl_setting.setOnClickListener(this);
        rl_mycollection.setOnClickListener(this);
        rl_scan.setOnClickListener(this);
        rl_partner.setOnClickListener(this);
        qrCodeBtn.setOnClickListener(this);

        ll_follow.setOnClickListener(this);
        ll_fans.setOnClickListener(this);
        ll_score.setOnClickListener(this);
//        myListView.addHeaderView(headView);
//        myListView.setAdapter(adapter);
    }

    private void reqData() {
        headInfoManager.headinfo(GlobalContext.getAccountId(), GlobalContext.getAccountId());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.headIcon:
                /** 点击放大图片 */
                ArrayList<String> urls2 = new ArrayList<>();
                urls2.add(GlobalContext.cdndownUrl + GlobalContext.getHeadPic());
                Utils.imageBrower(getContext(), 0, urls2);
                break;
            case R.id.head_info_relative:
                /** 跳转到完善资料 */
                intent(PerfectInfoActivity.class);
                break;
            case R.id.rl_Auth:
                if (!GlobalContext.getPerfectData()) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(getContext());
                } else {
                    /** 跳转到行业认证 */
                    intent(IndustryAuthActivity.class);
                }
                break;
            case R.id.rl_prefect_info:
                /** 跳转到完善资料*/
                intent(PerfectInfoActivity.class);
                break;
            case R.id.rl_myquestion:
                /** 跳转到我的问答 */
                intent(MyQAnswerActivity.class);
                break;
            case R.id.rl_anonymous:
                /** 跳转到心情 */
                intent(MyAmActivity.class);
                break;
            case R.id.rl_collection:
                /** 跳转到我的收藏 */
                intent(MyCollectionActivity.class);
                break;
//            case R.id.rl_score:
//                intent(MyScoreActivity.class);
//                break;
            case R.id.rl_scan:
                if (!GlobalContext.getPerfectData()) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(getContext());
                    return;
                }
                // 扫一扫
                PermissionUtils.getInstance().intentToScan(getActivity());
                break;
            case R.id.rl_sets:
                /** 跳转到设置 */
                intent(SettingActivity.class);
                break;
            case R.id.qrcode_Imagebutton:
                if (!GlobalContext.getPerfectData()) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(getContext());
                } else {
                    /**    跳转到二维码界面	*/
                    intent(MyQRCodeActivity.class);
                }
                break;
            case R.id.rl_partner:
                intent(PartnerActivity.class);
                break;
            case R.id.follow_ll: // 关注
                Intent followIntent = new Intent();
                followIntent.putExtra(Const.INTENT_TITLE, getResources().getString(R.string.follow));
                followIntent.putExtra(Const.INTENT_ID, GlobalContext.getAccountId());
                followIntent.setClass(getActivity(), FollowListActivity.class);
                startActivity(followIntent);
                break;
            case R.id.fans_ll: // 粉丝
                Intent fansIntent = new Intent();
                fansIntent.putExtra(Const.INTENT_ID, GlobalContext.getAccountId());
                fansIntent.setClass(getActivity(), FansListActivity.class);
                startActivity(fansIntent);
                break;
            case R.id.score_ll:
                intent(MyScoreActivity.class);
                break;

            default:
                break;
        }

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    private void intent(Class cls) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), cls);
        startActivity(intent);
    }

    @Override
    public void imageChange(String headCachePath) {
        if (null != this) {
            Glide.with(this)
                    .load(new File(headCachePath))
                    .centerCrop()
                    .placeholder(R.drawable.default_head_icon)
                    .crossFade()
                    .override(Utils.dip2px(getContext(), 40), Utils.dip2px(getContext(), 40))
                    .bitmapTransform(new GlideCircleTransform(getContext()))
                    .thumbnail(0.1f)
                    .into(headIV);
        }
    }

    @Override
    public void dataChanged(String nickName, String headPic, String sex, String signate, String label) {
        prefectInfoRl.setVisibility(View.GONE);
        GlobalContext.setLabel(label);
        labelTV.setText(label);
        Integer sexFlag = null;
        if (sex.equals("男")) {
            sexFlag = 1;
        } else if (sex.equals("女")) {
            sexFlag = 0;
        }
        Utils.showSex(getContext(), sexFlag, sexIV);
        signateTV.setText("简介：" + signate);
        nickNameTV.setText(nickName);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("FourthFragment"); //统计页面，"MainScreen"为页面名称，可自定义
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("FourthFragment");
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.fourth_fragment;
    }

    @Override
    protected void initView(View view) {
        initManager();
        initFragmentView(view);
        addHeadView(view);
        addListener();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (null == scoreUpdateReceiver) {
            // 动态注册广播
            IntentFilter filter = new IntentFilter();
            filter.addAction(ACTION_SCORE_UPDATE);
            scoreUpdateReceiver = new ScoreUpdateReceiver();
            // 注册前先移除广播
            getContext().registerReceiver(scoreUpdateReceiver, filter);
        }
    }

    @Override
    public void onFragmentFirstVisible() {
        super.onFragmentFirstVisible();
        reqData();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        /**    注释这行代码，防止界面跳转时，界面被回收	*/
        super.onSaveInstanceState(outState);
    }

    @Override
    public void updateScore() {
        try {
            GlobalUserData userData = new GlobalUserData();
            partnerScoreTV.setText(userData.getScore() + "");
            // 积分满300 自动显示合伙人图标
            if (userData.getScore() >= 300) {
                partnerIV.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onHeadFailure(int errorCode, String errorMsg) {
//        pullListView.onRefreshComplete(false, false);
        swipeLayout.setRefreshing(false);
    }

    @Override
    public void onHeadSuccess(HeadInfoData objdata) {
//        pullListView.onRefreshComplete(false, false);
        swipeLayout.setRefreshing(false);
        // 通知积分改变
        display(objdata);
    }

    /**
     * 更新用户头像信息
     *
     * @param data
     */
    private void display(HeadInfoData data) {
        // 保存合伙人和积分数据
        GlobalUserData userData = new GlobalUserData();
        userData.setScore(data.getScore());
        userData.setPartner(data.getPartner());
        // 更新用户数据
        GlobalContext.setHeadPic(data.getHeadPic());
        GlobalContext.setNiceName(data.getRealName());
        GlobalContext.setLabel(data.getLabel());
        GlobalContext.setSex(data.getSex());
        GlobalContext.setIndustryAuthority(data.getIsIndustryAuthority());
        GlobalContext.setSignate(data.getDescribe());
        GlobalContext.setPerfectData(data.getIsPerfectData());
        PictureDownloadUtils.displayHeadImage(getContext(), headIV, GlobalContext.getHeadPic());
        nickNameTV.setText(GlobalContext.getNiceName() == null ? "" : GlobalContext.getNiceName());
        labelTV.setText(GlobalContext.getLabel() == null ? "" : GlobalContext.getLabel());
        Utils.showSex(getContext(), GlobalContext.getSex(), sexIV);

        followTV.setText(data.getFollowCount() + "");
        fansTV.setText(data.getFansCount() + "");
        partnerScoreTV.setText(data.getScore() + "");

        signateTV.setText(GlobalContext.getSignate() == null ? "简介：暂无" : "简介：" + GlobalContext.getSignate());
        if (GlobalContext.getIndustryAuthority()) {
            addV.setVisibility(View.VISIBLE);
            authStatusTV.setText(getResources().getString(R.string.already_auth));
            authStatusTV.setTextColor(getResources().getColor(R.color.edit_hint_color));
        } else {
            addV.setVisibility(View.GONE);
            authStatusTV.setText(getResources().getString(R.string.no_auth));
            authStatusTV.setTextColor(getResources().getColor(R.color.already_auth_color));
        }
        if (GlobalContext.getPerfectData()) {
            prefectInfoRl.setVisibility(View.GONE);
        } else {
            prefectInfoRl.setVisibility(View.VISIBLE);
        }

        // 通知合伙人更新
        headImageManger.partnerNotify(data.getPartner());
        // 通知积分更新
        ScoreChangeManager scoreChangeManager = ScoreChangeManager.getInstance();
        scoreChangeManager.updateScore();
    }


    private class ScoreUpdateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (ACTION_SCORE_UPDATE == intent.getAction()) {
                String content = intent.getStringExtra(INTENT_DATA);
                processContent(content);
            }
        }

    }

    /**
     * 在service中已经保存了积分到GlobalUserData 在这里不再重复保存，只通知界面更新UI
     *
     * @param content
     */
    private void processContent(String content) {
        SyncInfoData syncData = JsonUtil.toObject(content, SyncInfoData.class);
        if (null != syncData && null != syncData.action) {
            GlobalUserData userData = new GlobalUserData();
            if (syncData.action.equals(Const.SyncInsturyKey)) {
                if (null != syncData.args.getAsJsonObject().get(Const.SyncInsturyValue)) {
//                    GlobalContext.setIndustryAuthority(syncData.args.getAsJsonObject().get(Const.SyncInsturyValue).getAsBoolean());
                    // 更新行业认证图标

                }
                if (null != syncData.args.getAsJsonObject().get(Const.SyncScoreValue)) {
                    ScoreChangeManager scoreChangeManager = ScoreChangeManager.getInstance();
                    scoreChangeManager.updateScore();
                }
            } else if (syncData.action.equals(Const.SyncScoreKey)) {
                if (null != syncData.args.getAsJsonObject().get(Const.SyncScoreValue)) {
                    ScoreChangeManager scoreChangeManager = ScoreChangeManager.getInstance();
                    scoreChangeManager.updateScore();
                }
            } else if (syncData.action.equals(Const.updatePartnerTarget)) {
                if (null != syncData.args.getAsJsonObject().get(Const.partner)) {
                    int partner = syncData.args.getAsJsonObject().get(Const.partner).getAsInt();
                    userData.setPartner(partner);
                    // 通知更新合伙人UI
                    headImageManger.partnerNotify(partner);
                }
            }
        }
    }


    @Override
    public void partnerNotify(int partner) {
        if (1 == partner) {
            partnerIV.setVisibility(View.VISIBLE);
        } else {
            partnerIV.setVisibility(View.GONE);
        }
    }


}